package com.sky.component;

import com.sky.constant.MessageQueueTopicConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: invictusQAQ
 * @Date: 2023-09-04-20:32
 * @Description: 处理超时订单
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = MessageQueueTopicConstant.TIMEOUT_ORDER_TOPIC,consumerGroup = "${rocketmq.consumer.group}",
        messageModel = MessageModel.CLUSTERING,selectorType = SelectorType.TAG,selectorExpression = MessageQueueTopicConstant.TIMEOUT_ORDER_TAG)
public class DelayMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void onMessage(MessageExt messageExt){
        String orderId=new String(messageExt.getBody());
        log.info("接收到延迟消息{}",orderId);
        Orders order=orderMapper.getById(Long.valueOf(orderId));
        //订单存在且未支付则自动取消
        if(order!=null&&order.getStatus().equals(Orders.PENDING_PAYMENT)){
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("支付超时，自动取消");
            orderMapper.update(order);
        }
    }

}
